// Services/MenuService.cs
using Microsoft.AspNetCore.Components;
using StudentVideo.Client.Common.Attributes;
using StudentVideo.Client.Common.Types;
using System.Reflection;
using System.Text.Json;

namespace StudentVideo.Client.Services;

public class MenuMateGroup : MenuMateGroupData {
   public required List<MenuMateItem> Items { get; set; }
}

public class MenuMateService {
   public static readonly IReadOnlyList<MenuMateGroupData> Options = [
      new () { Title = "公共", Name = "default", Order = 1 },
      new () { Title = "管理", Name = "student", Order = 2 },
      new () { Title = "用户管理", Name = "admin", Order = 3 },
   ];

   public static (List<MenuMateGroup>, List<MenuMateItem>) GetMenuGroups() {
      var menuItems = new List<MenuMateItem>();
      var assembly = Assembly.GetExecutingAssembly();

      // 扫描所有组件
      foreach (var type in assembly.GetTypes()) {
         var routeAttribute = type.GetCustomAttribute<RouteAttribute>();
         var menuAttribute = type.GetCustomAttribute<MenuMateAttribute>();

         if (routeAttribute != null && menuAttribute != null) {

            var template = routeAttribute.Template.Trim('/');
            var segments = template.Split('/', StringSplitOptions.RemoveEmptyEntries);
            var group = segments.Length > 1 ? segments[0] : "default";

            var item = new MenuMateItem {
               Title = menuAttribute.Title,
               Group = group,
               Order = menuAttribute?.Order ?? 1,
               Url = routeAttribute.Template
            };

            menuItems.Add(item);
            string json = JsonSerializer.Serialize(item);
         }
      }

      List<MenuMateGroup> list = [.. menuItems
         .GroupBy(m => m.Group)
         .Select(g => {
            var groupOption = Options.FirstOrDefault(e => e.Name == g.Key);
            if(groupOption is null)
               return null!;

            return new MenuMateGroup {
               Title = groupOption.Title,
               Name = groupOption.Name,
               Order = groupOption?.Order ?? 1,
               Icon = groupOption?.Icon,
               Items = [.. g.OrderBy(i => i.Order)]
            };
         })
         .Where(g => g != null)
         .OrderBy(g => g!.Order)
      ];

      // 按分组聚合
      return (list, menuItems);
   }
}

public class MenuMateItemBase {
   /// <summary>
   /// 显示名称
   /// </summary>
   public required string Title { get; set; }
   /// <summary>
   /// 地址
   /// </summary>
   public required string Url { get; set; }
}

public class MenuMateItem : MenuMateItemBase {

   /// <summary>
   /// 组别
   /// </summary>
   public required string Group { get; set; }

   /// <summary>
   /// 排序
   /// </summary>
   public int Order { get; set; }
   /// <summary>
   /// 图标
   /// </summary>
   public RenderFragment? Icon { get; set; }
}
